<script setup>
import {getCurrentInstance, reactive, ref, watch} from "vue";
import {cloneDeep} from "lodash";
import {checkPwdStrong, enumToArray} from "@/utils/utils";
import {userGenderList, userStatusList} from "@/enum/enum";
import {addSysUser, getSysUser, updateSysUser} from "@/api/system/user";
import {md5} from "js-md5";
import {listSysRole} from "@/api/system/role";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  userId: undefined,
  userName: '',
  nickName: '',
  password: '',
  email: '',
  phonenumber: '',
  sex: 2,
  status: 1,
  roleId: ''
})
const rules = reactive({
  userName: [
    {required: true, message: '请输入用户账号', trigger: 'blur'}
  ],
  nickName: [{required: true, message: '请输入用户昵称', trigger: 'blur'}],
  email: [
    {
      pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ],
  phonenumber: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur'
    },
    {
      pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  roleId: [
    {
      required: true,
      message: '请选择角色',
      trigger: 'blur'
    }
  ]
})
const userGenderOptions = enumToArray(userGenderList)
const userStatusOptions = enumToArray(userStatusList)
const formType = ref('create')
const msgText = ref()
const pwdPercentage = ref(0)
const pwdColor = ref("#FF5340")
const pwdFormatF = ref('弱')
const roleList = ref([])

const getRoleList = async () => {
  const {data} = await listSysRole({pageSize: -1});
  roleList.value = data.list;
}

const open = async (userId, type = 'create') => {
  formType.value = type;
  resetForm();
  await getRoleList()
  if (type === 'create') {
  } else {
    const {data} = await getSysUser(userId);
    formData.value = {
      ...data,
      password: ''
    }
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  const result = await formRef.value.validate();
  if (result) {
    return false;
  }
  let data = cloneDeep(formData.value);
  if (data.userId === undefined) {
    data.password = md5(data.password)
    await addSysUser(data);
    proxy.$modal.okNotify('新增成功');
  } else {
    delete data.password;
    await updateSysUser(data);
    proxy.$modal.okNotify('修改成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    userId: undefined,
    userName: '',
    nickName: '',
    password: '',
    email: '',
    phonenumber: '',
    sex: 2,
    status: 1,
    roleId: ''
  }
}

watch(() => formData.value.password, (newVal) => {
  msgText.value = checkPwdStrong(newVal);
  if (msgText.value > 1 || msgText.value === 1) {
    pwdPercentage.value = 0.3;
    pwdColor.value = "#FF5340";
    pwdFormatF.value = '弱'
  }
  if (msgText.value > 2 || msgText.value === 2) {
    pwdPercentage.value = 0.6;
    pwdColor.value = "#FFB640"
    pwdFormatF.value = '中'
  }
  if (msgText.value === 4) {
    pwdPercentage.value = 1;
    pwdColor.value = "#25DC1B"
    pwdFormatF.value = '强'
  }
}, {
  immediate: true
})

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" :modalTitle="`${formType === 'create' ? '新建' : '编辑'}用户`" modalWidth="1000px"
               @submit="handleSubmit">
    <a-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <a-row :gutter="4" justify="space-between">
        <a-col :span="12">
          <a-form-item label="用户账号" field="userName">
            <a-input v-model="formData.userName" placeholder="请输入用户账号"
                     :disabled="formData.userId !== undefined"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用户昵称" field="nickName">
            <a-input v-model="formData.nickName" placeholder="请输入用户昵称"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="4" justify="space-between">
        <a-col :span="12">
          <a-form-item label="登录密码" field="password" style="margin-bottom: unset" :required="formType === 'create'"
                       :rules="[
              {
                required: formType === 'create',
                message: '请输入密码',
                trigger: 'blur'
              }
            ]">
            <a-input-password v-model="formData.password"
                     :placeholder="formType === 'create' ? '请输入登录密码' : ''"
                     :disabled="formData.userId !== undefined"/>
          </a-form-item>
          <div style="margin: 18px 0 18px 100px" v-if="formType === 'create'">
            <a-progress :percent="pwdPercentage" :stroke-width="14" :color="pwdColor">
              <template v-slot:text="scope">
                {{ pwdFormatF }}
              </template>
            </a-progress>
          </div>
        </a-col>
        <a-col :span="12">
          <a-form-item label="电子邮箱" field="email">
            <a-input v-model="formData.email" placeholder="请输入电子邮件"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="4" justify="space-between">
        <a-col :span="12">
          <a-form-item label="手机号码" field="phonenumber">
            <a-input v-model="formData.phonenumber" placeholder="请输入手机号码"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="性别" field="sex">
            <a-select v-model="formData.sex" placeholder="请选择用户性别">
              <a-option v-for="item in userGenderOptions" :key="item.value" :value="item.value" :label="item.label"/>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="4" justify="space-between">
        <a-col :span="12">
          <a-form-item label="用户状态" field="status">
            <a-select v-model="formData.status" placeholder="请选择用户状态">
              <a-option v-for="item in userStatusOptions" :key="item.value" :value="item.value" :label="item.label"/>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="角色" field="roleId">
            <a-select v-model="formData.roleId" placeholder="请选择角色">
              <a-option v-for="item in roleList" :key="item.id" :value="item.id" :label="item.roleName"
                        :disabled="item.id === 1"/>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="备注" field="remark" label-col-flex="80px">
        <a-textarea v-model="formData.remark" placeholder="请输入内容"/>
      </a-form-item>
    </a-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
